package com.lxk.ums.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxk.ums.controller.app.vo.AppAddressParam;
import com.lxk.ums.controller.app.vo.AppAddressUpdateParam;
import com.lxk.ums.controller.app.vo.AppDefaultParam;
import com.lxk.ums.domain.UmsUserAddress;
import com.lxk.ums.domain.bo.UmsUserAddressBo;
import com.lxk.ums.domain.vo.UmsUserAddressVo;
import com.lxk.ums.mapper.UmsUserAddressMapper;
import com.lxk.ums.service.IUmsUserAddressService;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.enums.CommonStatusEnum;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.domain.BaseEntity;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户收货地址Service业务层处理
 *
 * @author soda
 * @date 2024-07-11
 */
@RequiredArgsConstructor
@Service
public class UmsUserAddressServiceImpl implements IUmsUserAddressService {

    private final UmsUserAddressMapper baseMapper;

    /**
     * 查询IdList用户收货地址Map
     */
    @Override
    public Map<Long, UmsUserAddressVo> queryMapByIdList(List<Long> idList) {
        return this.queryByIdList(idList).stream().collect(Collectors.toMap(UmsUserAddressVo::getId, v -> v));
    }

    /**
     * 查询用户收货地址Map
     */
    @Override
    public Map<Long, UmsUserAddressVo> queryMap(UmsUserAddressBo bo) {
        return this.queryList(bo).stream().collect(Collectors.toMap(UmsUserAddressVo::getId, v -> v));
    }

    /**
     * 查询用户收货地址IdList
     */
    @Override
    public List<UmsUserAddressVo> queryByIdList(List<Long> idList) {
        if (CollUtil.isEmpty(idList)) {
            return CollUtil.newArrayList();
        }
        LambdaQueryWrapper<UmsUserAddress> lqw = Wrappers.lambdaQuery();
        lqw.in(UmsUserAddress::getId, idList);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询用户收货地址
     *
     * @param id 主键
     * @return 用户收货地址
     */
    @Override
    public UmsUserAddressVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询用户收货地址列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户收货地址分页列表
     */
    @Override
    public TableDataInfo<UmsUserAddressVo> queryPageList(UmsUserAddressBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<UmsUserAddress> lqw = buildQueryWrapper(bo);
        Page<UmsUserAddressVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户收货地址列表
     *
     * @param bo 查询条件
     * @return 用户收货地址列表
     */
    @Override
    public List<UmsUserAddressVo> queryList(UmsUserAddressBo bo) {
        LambdaQueryWrapper<UmsUserAddress> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<UmsUserAddress> buildQueryWrapper(UmsUserAddressBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<UmsUserAddress> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(UmsUserAddress::getId);
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null, UmsUserAddress::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.between(params.get("beginUpdateTime") != null && params.get("endUpdateTime") != null, UmsUserAddress::getUpdateTime, params.get("beginUpdateTime"), params.get("endUpdateTime"));
        lqw.eq(bo.getUserId() != null, UmsUserAddress::getUserId, bo.getUserId());
        lqw.eq(bo.getLongitude() != null, UmsUserAddress::getLongitude, bo.getLongitude());
        lqw.eq(bo.getLatitude() != null, UmsUserAddress::getLatitude, bo.getLatitude());
        lqw.like(StringUtils.isNotBlank(bo.getRealName()), UmsUserAddress::getRealName, bo.getRealName());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), UmsUserAddress::getPhone, bo.getPhone());
        lqw.eq(bo.getProvinceId() != null, UmsUserAddress::getProvinceId, bo.getProvinceId());
        lqw.eq(StringUtils.isNotBlank(bo.getProvince()), UmsUserAddress::getProvince, bo.getProvince());
        lqw.eq(bo.getCityId() != null, UmsUserAddress::getCityId, bo.getCityId());
        lqw.eq(StringUtils.isNotBlank(bo.getCity()), UmsUserAddress::getCity, bo.getCity());
        lqw.eq(bo.getDistrictId() != null, UmsUserAddress::getDistrictId, bo.getDistrictId());
        lqw.eq(StringUtils.isNotBlank(bo.getDistrict()), UmsUserAddress::getDistrict, bo.getDistrict());
        lqw.eq(StringUtils.isNotBlank(bo.getDetail()), UmsUserAddress::getDetail, bo.getDetail());
        lqw.eq(bo.getDefaultStatus() != null, UmsUserAddress::getDefaultStatus, bo.getDefaultStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getStreet()), UmsUserAddress::getStreet, bo.getStreet());
        return lqw;
    }

    /**
     * 新增用户收货地址
     *
     * @param bo 用户收货地址
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(UmsUserAddressBo bo) {
        UmsUserAddress add = MapstructUtils.convert(bo, UmsUserAddress.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户收货地址
     *
     * @param bo 用户收货地址
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(UmsUserAddressBo bo) {
        UmsUserAddress update = MapstructUtils.convert(bo, UmsUserAddress.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(UmsUserAddress entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户收货地址信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public UmsUserAddressVo getAddress(Long addressId, Long userId) {
        //校验参数
        if (addressId != null) {
            UmsUserAddressVo address = baseMapper.selectVoById(addressId);
            if (address == null) {
                throw new ServiceException("地址不存在");
            }
            if (!address.getUserId().equals(userId)) {
                throw new ServiceException("地址不属于该用户");
            }
            return address;
        }
        return null;
    }

    @Override
    public UmsUserAddressVo getAddressIfDefault(Long userId, Long addressId) {
        //校验参数
        if (addressId != null) {
            UmsUserAddressVo address = baseMapper.selectVoById(addressId);
            if (address == null) {
                //获取默认地址
                LambdaQueryWrapper<UmsUserAddress> lqw = Wrappers.lambdaQuery();
                lqw.eq(UmsUserAddress::getUserId, userId);
                lqw.eq(UmsUserAddress::getDefaultStatus, CommonStatusEnum.ENABLE.getStatus());
                address = baseMapper.selectVoOne(lqw);
                if (address == null) {
                    throw new ServiceException("地址不存在");
                }
            }
            if (!address.getUserId().equals(userId)) {
                throw new ServiceException("地址不属于该用户");
            }
            return address;
        }
        return null;
    }

    @Override
    public Boolean addAddress(AppAddressParam appAddressParam) {
        Long userId = LoginHelper.getUserId();
        UmsUserAddress umsUserAddress = BeanUtil.toBean(appAddressParam, UmsUserAddress.class);
        umsUserAddress.setUserId(userId);
        // 判断是否默认地址
        if (UmsUserAddress.defaultStatus.DEFAULT_NO.getCode().equals(appAddressParam.getDefaultStatus())) {
            return baseMapper.insert(umsUserAddress) > 0;
        }
        // 获取默认地址
        UmsUserAddressVo umsUserAddressVo = checkDefault(userId);
        if (ObjectUtil.isEmpty(umsUserAddressVo)) {
            return baseMapper.insert(umsUserAddress) > 0;
        }
        Boolean flag = updateAddressDefault(umsUserAddressVo.getId(), umsUserAddressVo.getDefaultStatus(), UmsUserAddress.defaultStatus.DEFAULT_NO.getCode());
        if (flag) {
            return baseMapper.insert(umsUserAddress) > 0;
        }
        return false;
    }

    @Override
    public Boolean updateAddress(AppAddressUpdateParam appAddressUpdateParam) {
        UmsUserAddress umsUserAddress = MapstructUtils.convert(appAddressUpdateParam, UmsUserAddress.class);
        return baseMapper.updateById(umsUserAddress) > 0;
    }

    @Override
    public Boolean updateDefault(AppDefaultParam appDefaultParam) {
        if (UmsUserAddress.defaultStatus.DEFAULT_YES.getCode().equals(appDefaultParam.getNewDefaultStatus())) {
            // 查看是否有默认地址
            UmsUserAddressVo umsUserAddressVo = checkDefault(LoginHelper.getUserId());
            if (ObjectUtil.isEmpty(umsUserAddressVo)) {
                Boolean aBoolean = updateAddressDefault(appDefaultParam.getAddressId(), appDefaultParam.getStartDefaultStatus(), appDefaultParam.getNewDefaultStatus());
                return aBoolean;
            }
            Boolean aBoolean = updateAddressDefault(umsUserAddressVo.getId(), umsUserAddressVo.getDefaultStatus(), UmsUserAddress.defaultStatus.DEFAULT_NO.getCode());
            if (aBoolean) {
                Boolean aBoolean1 = updateAddressDefault(appDefaultParam.getAddressId(), appDefaultParam.getStartDefaultStatus(), appDefaultParam.getNewDefaultStatus());
                return aBoolean1;
            }
        }
        return updateAddressDefault(appDefaultParam.getAddressId(), appDefaultParam.getStartDefaultStatus(), appDefaultParam.getNewDefaultStatus());
    }

    @Override
    public Page<UmsUserAddressVo> queryByPageList(PageQuery pageQuery) {
        LambdaQueryWrapper<UmsUserAddress> wrapper = Wrappers.<UmsUserAddress>lambdaQuery();
        wrapper.eq(UmsUserAddress::getUserId, LoginHelper.getUserId());
        wrapper.orderByDesc(BaseEntity::getCreateTime);
        return baseMapper.selectVoPage(pageQuery.build(), wrapper);
    }

    @Override
    public boolean deleteAddressById(Long addressId) {
        if (addressId == null) {
            throw new ServiceException("地址id不能为空");
        }
        LambdaQueryWrapper<UmsUserAddress> lqw = Wrappers.lambdaQuery();
        lqw.eq(UmsUserAddress::getId, addressId);
        lqw.eq(UmsUserAddress::getUserId, LoginHelper.getUserId());
        return baseMapper.delete(lqw) > 0;
    }

    @Override
    public UmsUserAddressVo getDefaultAddress(Long userId) {
        LambdaQueryWrapper<UmsUserAddress> lqw = Wrappers.lambdaQuery();
        lqw.eq(UmsUserAddress::getUserId, userId);
        lqw.eq(UmsUserAddress::getDefaultStatus, CommonStatusEnum.ENABLE.getStatus());
        UmsUserAddressVo vo = baseMapper.selectVoOne(lqw);
        return vo;
    }

    /**
     * 查看是否有默认地址
     *
     * @param userId
     */
    private UmsUserAddressVo checkDefault(Long userId) {
        LambdaQueryWrapper<UmsUserAddress> wrapper = Wrappers.<UmsUserAddress>lambdaQuery();
        wrapper.eq(UmsUserAddress::getUserId, userId)
            .eq(UmsUserAddress::getDefaultStatus, UmsUserAddress.defaultStatus.DEFAULT_YES.getCode());
        return baseMapper.selectVoOne(wrapper);
    }

    /**
     * 根据id修改默认地址状态
     *
     * @param userAddressId
     * @param startDefaultStatus
     * @param newDefaultStatus
     */
    public Boolean updateAddressDefault(Long userAddressId, Integer startDefaultStatus, Integer newDefaultStatus) {
        LambdaUpdateWrapper<UmsUserAddress> wrapper = Wrappers.<UmsUserAddress>lambdaUpdate();
        wrapper.eq(UmsUserAddress::getId, userAddressId)
            .eq(UmsUserAddress::getDefaultStatus, startDefaultStatus)
            .set(UmsUserAddress::getDefaultStatus, newDefaultStatus);
        return baseMapper.update(null, wrapper) > 0;
    }
}
